package com;


import com.alibaba.fastjson.JSON;
import com.entity.dto.ApiResult;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class HandlerInterceptorS implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("text/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String token = request.getHeader("token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        if (token != null){
            try (Jedis jedis = new Jedis("47.106.226.199", 6429)) {
                jedis.auth("666t01");
                if (jedis.get(token)!=null){
                    return true;
                }else {
                    PrintWriter out = response.getWriter();
                    out.print(JSON.toJSONString(new ApiResult(500,"验证登录已过期，重新登录","String",null)));
                    out.flush();
                    out.close();
                    return  false;
                }
            }

        }
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(new ApiResult(500,"请先登录","String",null)));
        out.flush();
        out.close();
        return  false;
    }
}
